#include <iostream>
#include <SFML/Graphics.hpp>
#include "../../include/GUI/Slide.hpp"

using namespace std;

namespace GUI
{
    Slide::Slide(Engine &Moteur, int value, int max_value) : Widget(Moteur)
    {
        m_value = value;
        m_max_value = max_value;

        m_sprite.SetImage(*m_Moteur.Graphic()->GetGUIImage(8));
        m_rects.push_back(sf::IntRect(0,0,200,20));
        m_rects.push_back(sf::IntRect(200,0,12,20));

        m_dimensions.width = m_rects[0].Width-4*m_padding/3;
        m_dimensions.height = m_rects[0].Height;

        m_deplacement = false; // Le curseur est immobile par defaut
    }

    void Slide::SetValue(int value)
    {
        m_value = value;
    }
    int Slide::GetValue()
    {
        return m_value;
    }

    bool Slide::IsMax()
    {
        if(m_value == m_max_value)
            return true;
        else
            return false;
    }
    bool Slide::IsMin()
    {
        if(m_value == 0)
            return true;
        else
            return false;
    }

    void Slide::Afficher()
    {
        m_sprite.SetSubRect(m_rects[0]);
        m_sprite.SetPosition(m_position.x, m_position.y);
        m_Moteur.Graphic()->Draw(m_sprite);

        m_sprite.SetSubRect(m_rects[1]);
        m_sprite.SetPosition(m_position.x + ((m_value*100)/m_max_value)*2 - m_rects[1].Width/2, m_position.y);
        m_Moteur.Graphic()->Draw(m_sprite);
    }
    void Slide::UpdateEvent()
    {
        int x = m_Moteur.App().GetInput().GetMouseX();
        int y = m_Moteur.App().GetInput().GetMouseY();
        int pos_x = m_position.x + ((m_value*100)/m_max_value)*2 - m_rects[1].Width/2;
        int pos_y = m_position.y;

        if(x > pos_x and y > pos_y and x < pos_x+m_rects[1].Width and y < pos_y+m_rects[1].Height)
        {
            if(m_Moteur.Event()->Type == sf::Event::MouseButtonPressed and m_Moteur.App().GetInput().IsMouseButtonDown(sf::Mouse::Left) and !m_Moteur.App().GetInput().IsMouseButtonDown(sf::Mouse::Right))
            {
                m_deplacement = true;
            }
        }

        if(m_deplacement)
        {
            if(x > m_position.x - m_rects[1].Width/2 and x <= m_position.x + m_rects[0].Width + m_rects[1].Width/2)
            {
                m_value = (((x-m_position.x)*m_max_value)/(m_rects[0].Width));
                if(m_value > m_max_value)
                    m_value = m_max_value;
                else if(m_value < 0)
                    m_value = 0;
            }
        }

        if(m_deplacement == true and m_Moteur.Event()->Type == sf::Event::MouseButtonReleased)
        {
            m_deplacement = false;
        }
    }
}
